import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';

class WindowTitleBar extends StatefulWidget {
  final bool isBack;
  const WindowTitleBar({super.key, this.isBack = false});

  @override
  State<WindowTitleBar> createState() => _WindowTitleBarState();
}

class _WindowTitleBarState extends State<WindowTitleBar> {
  bool _isAlwaysOnTop = false;

  void _toggleAlwaysOnTop() {
    setState(() {
      _isAlwaysOnTop = !_isAlwaysOnTop;
      windowManager.setAlwaysOnTop(_isAlwaysOnTop);
    });
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      windowManager.isAlwaysOnTop().then((value) {
        setState(() {
          _isAlwaysOnTop = value;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return WindowTitleBarBox(
      child: Container(
        color: theme.primaryContainer,
        child: Row(
          children: [
            if (widget.isBack)
              InkWell(
                onTap: () => Navigator.of(context).pop(),
                child: Padding(
                  padding: const EdgeInsets.only(left: 10),
                  child: Icon(
                    Icons.keyboard_backspace,
                    size: 22,
                    color: theme.onSurface,
                  ),
                ),
              ),
            Expanded(child: MoveWindow()),
            WindowButton(
              colors: WindowButtonColors(
                iconNormal: _isAlwaysOnTop
                    ? theme.primary
                    : theme.onSurface,
              ),
              onPressed: _toggleAlwaysOnTop,
              iconBuilder: (buttonContext) => Icon(
                Icons.push_pin,
                size: 14,
                color: _isAlwaysOnTop
                    ? theme.primary
                    : theme.onSurface,
              ),
            ),
            MinimizeWindowButton(
              colors: WindowButtonColors(
                iconNormal: theme.onSurface,
              ),
            ),
            MaximizeWindowButton(
              colors: WindowButtonColors(
                iconNormal: theme.onSurface,
              ),
            ),
            CloseWindowButton(
              colors: WindowButtonColors(
                iconNormal: theme.onSurface,
                mouseOver: Colors.red,
                mouseDown: Colors.redAccent,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
